package com.t4l.client.screens.login;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DecoratedPopupPanel;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.t4l.client.T4l;
import com.t4l.client.images.Images;
import com.t4l.client.language.Lang;
import com.t4l.client.screens.login.signup.Signup;
import com.t4l.client.services.login.LoginService;
import com.t4l.client.services.login.LoginServiceAsync;

public class Login extends Composite {

	private LoginServiceAsync loginService = GWT.create(LoginService.class);

	private static LoginUiBinder uiBinder = GWT.create(LoginUiBinder.class);

	interface LoginUiBinder extends UiBinder<Widget, Login> {
	}

	@UiField
	Label signinLabel;

	@UiField
	HTMLPanel signinButton;

	@UiField
	Label loginLabel;

	@UiField
	TextBox login;

	@UiField
	Label passwordLabel;

	@UiField
	TextBox password;

	@UiField
	Image loginWithFacebook;

	@UiField
	Anchor signup;

	DecoratedPopupPanel popup;

	Signup signupPanel = null;
	DialogBox dialogBox = null;

	T4l t4l;

	public Login(T4l t4l) {
		initWidget(uiBinder.createAndBindUi(this));
		initButtonEvents();
		initFieldEvents();
		initImagesEvents();
		popup = new DecoratedPopupPanel(true);
		popup.setWidget(new HTML(Lang.get().mandatoryField()));
		signup.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				if (dialogBox == null) {
					dialogBox = new DialogBox();
				}
				dialogBox.setText("Registro de nuevo usuario");
				dialogBox.setModal(true);
				dialogBox.setAnimationEnabled(true);
				if (signupPanel == null) {
					signupPanel = new Signup(dialogBox);
				}
				dialogBox.setWidget(signupPanel);
				dialogBox.center();
			}
		});
		this.t4l = t4l;
	}

	private void initImagesEvents() {
		loginWithFacebook.setTitle("Iniciar usando facebook");
		loginWithFacebook.addDomHandler(new MouseOverHandler() {
			@Override
			public void onMouseOver(MouseOverEvent event) {
				DOM.setStyleAttribute(loginWithFacebook.getElement(),
						"backgroundColor", "#CCC");
			}
		}, MouseOverEvent.getType());
		loginWithFacebook.addDomHandler(new MouseOutHandler() {
			@Override
			public void onMouseOut(MouseOutEvent event) {
				DOM.setStyleAttribute(loginWithFacebook.getElement(),
						"backgroundColor", "");
			}
		}, MouseOutEvent.getType());
		loginWithFacebook.addDomHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				String fburl = "https://www.facebook.com/dialog/oauth?"
						+ "client_id=227716007243837&redirect_uri=http%3A//localhost%3A8080/Talk4Link/T4l.html%3Fgwt.codesvr%3D127.0.0.1%3A9997&scope=email,read_stream&"
						+ "response_type=token";
				Window.open(fburl, "_self", "");
			}
		}, ClickEvent.getType());
	}

	private void initFieldEvents() {

		KeyPressHandler keyHandler = new KeyPressHandler() {
			@Override
			public void onKeyPress(KeyPressEvent event) {
				if (event.getUnicodeCharCode() == KeyCodes.KEY_ENTER) {
					signin();
				}
			}
		};
		login.addKeyPressHandler(keyHandler);
		password.addKeyPressHandler(keyHandler);
	}

	@Override
	protected void onLoad() {
		super.onLoad();
		login.setFocus(true);
		loginLabel.setText(Lang.get().userName());
		passwordLabel.setText(Lang.get().password());
		signinLabel.setText(Lang.get().signin());
		loginWithFacebook.setResource(Images.get().facebook());
	}

	private void initButtonEvents() {
		signinButton.addDomHandler(new MouseOverHandler() {
			@Override
			public void onMouseOver(MouseOverEvent event) {
				DOM.setStyleAttribute(signinButton.getElement(),
						"textDecoration", "underline");
				DOM.setStyleAttribute(signinButton.getElement(),
						"backgroundColor", "#CCC");
			}
		}, MouseOverEvent.getType());
		signinButton.addDomHandler(new MouseOutHandler() {
			@Override
			public void onMouseOut(MouseOutEvent event) {
				DOM.setStyleAttribute(signinButton.getElement(),
						"textDecoration", "");
				DOM.setStyleAttribute(signinButton.getElement(),
						"backgroundColor", "");
			}
		}, MouseOutEvent.getType());
		signinButton.addDomHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				signin();
			}
		}, ClickEvent.getType());
	}

	protected void signin() {
		String user = login.getText();
		String _password = password.getText();
		if (user.length() <= 0) {
			int absoluteLeft = login.getElement().getAbsoluteLeft();
			showWarning(absoluteLeft);
			login.setFocus(true);
		} else if (_password.length() <= 0) {
			int absoluteLeft = password.getElement().getAbsoluteLeft();
			showWarning(absoluteLeft);
			password.setFocus(true);
		} else {
			loginService.validateT4LLogin(login.getText(), password.getText(),
					new AsyncCallback<String>() {
						@Override
						public void onSuccess(String result) {
							JSONValue parseStrict = JSONParser
									.parseStrict(result);
							t4l.setUserInfo(parseStrict.isObject());
							t4l.in();
						}

						@Override
						public void onFailure(Throwable caught) {
							Window.alert(caught.getMessage());
						}
					});
		}
	}

	private void showWarning(int absoluteLeft) {
		int clientHeight = Window.getClientHeight();
		popup.setPopupPosition(absoluteLeft, clientHeight - 85);
		popup.show();
		Timer timer = new Timer() {
			@Override
			public void run() {
				if (popup.isShowing()) {
					popup.hide();
				}
			}
		};
		timer.schedule(5000);
	}
}
